import React, { useMemo, useState } from 'react'
import { Popup, CascadePickerView, PickerView, Toast, TextArea, Switch } from 'antd-mobile'
import "@/assets/css/memoire.scss"
import "@/assets/css/hlthArchives.scss"
import {
    targetMap,
    getcurrentDates,
    dateStyle,
    genderStyle
} from "@/utils/historyUtil"
import dayjs from "dayjs"

import HeadBack from "@/components/HeadBack"

import { addUserTakings, delUserTakings } from "@/utils/dataUtil"
import { useLocation, useNavigate } from 'react-router-dom'
import { useSelector } from 'react-redux'

import unitImg from "@/assets/images/hospital/unit.png"
import addDurImg from "@/assets/images/hospital/add_dur.png"
import closeDurImg from "@/assets/images/hospital/close_dur.png"


const popTitList = ["选择用药开始时间", "选择用药结束时间", "时间"];

export default function AddMedication() {

    const location = useLocation();

    const navigator = useNavigate();

    //获取详情数据
    const detail = useSelector((state) => state.MedicatReducer.detail);

    //弹出层是否展示
    const [visible, setVisible] = useState(false);
    //点击哪一个索引
    const [count, setCount] = useState(0);
    //日期受控
    const [startDate, setStartDate] = useState(location.state.type === "update" && JSON.stringify(detail) !== '{}' ? detail.get("start").split("-") : getcurrentDates());
    //日期值
    const [startDateVal, setStartDateVal] = useState(location.state.type === "update" && JSON.stringify(detail) !== '{}' ? detail.get("start") : "");
    //日期受控
    const [endDate, setEndDate] = useState(location.state.type === "update" && JSON.stringify(detail) !== '{}' ? detail.get("end").split("-") : getcurrentDates());
    //日期值
    const [endDateVal, setEndDateVal] = useState(location.state.type === "update" && JSON.stringify(detail) !== '{}' ? detail.get("end") : "");
    //时间受控
    const [durationValue, setDurationValue] = useState([]);
    //用户选择的吃药时间，最大数组length为8
    const [durations, setDurations] = useState(location.state.type === "update" && JSON.stringify(detail) !== '{}' ? detail.get("times").toJS() : []);
    //用什么药的内容
    const [medVal, setMedVal] = useState(location.state.type === "update" && JSON.stringify(detail) !== '{}' ? detail.get('drugs') : "");
    // 补充内容
    const [supplyVal, setSupplyVal] = useState(location.state.type === "update" && JSON.stringify(detail) !== '{}' ? detail.get('remark') : "");
    //是否开启用药提醒
    const [tipSwitch, setTipSwitch] = useState(location.state.type === "update" && JSON.stringify(detail) !== '{}' ? detail.get('warn') : 1);





    //点击每一个选择框的确定按钮
    const clickConfirm = () => {
        switch (count) {
            case 0:
                if (endDateVal !== "" && !(dayjs(endDateVal).isAfter(dayjs(startDate.join("-"))) || dayjs(endDateVal).isSame(dayjs(startDate.join("-"))))) {
                    setStartDate(endDate);
                    setStartDateVal(endDate.join("-"));
                } else {
                    setStartDateVal(startDate.join("-"));
                }
                break;
            case 1:
                if (startDateVal !== "" && !(dayjs(endDate.join("-")).isAfter(dayjs(startDateVal)) || dayjs(endDate.join("-")).isSame(dayjs(startDateVal)))) {
                    setEndDate(startDate);
                    setEndDateVal(startDate.join("-"));
                } else {
                    setEndDateVal(endDate.join("-"));
                }
                break;
            case 2:
                if(durations.findIndex((item) => item === durationValue.join(":")) !== -1) {
                    setVisible(false);
                    Toast.show({
                        content: "设置的时间重复",
                        position: 'bottom'
                    })
                    return;
                }
                if(durations.length >= 8) {
                    setVisible(false);
                    return;
                }
                setDurations((dur) => {
                    const current = dur.concat();
                    current.push(durationValue.join(":"));
                    return current;
                });
                break;
        }
        setVisible(false);
    }

    //值的改变
    const valChanger = (val, index) => {
        switch (index) {
            case 0:
                setStartDate(val);
                break;
            case 1:
                setEndDate(val);
                break;
            case 2:
                setDurationValue(val);
                break;
        }

    }


    //开始日期值的变化
    const startDateChanger = (val) => {
        valChanger(val, 0);
    }
    //结束日期值的变化
    const endDateChanger = (val) => {
        valChanger(val, 1);
    }

    //时间值的变化
    const durationChanger = (val) => {
        valChanger(val, 2);
    }





    //点击每一个选择框的取消按钮
    const clickCancel = () => {
        setVisible(false);
    }

    //点击开始时间的item
    const clickItem = (index) => {
        setCount(index);
        setVisible(true);
    }

    //点击删除时间的item
    const clickDelDurItem = (i) => {
        const current = durations.concat();
        const currents = current.filter((item, index) => index !== i);
        setDurations(currents);
    }

    //补充内容改变
    const supplyChange = (val) => {
        setSupplyVal(val);
    }

    //保存按钮是否可点击
    const addmDisabled = useMemo(() => {
        return startDateVal.trim() !== "" &&  endDateVal.trim() !== "" && durations.length > 0 && medVal.trim() !== ""
    }, [startDateVal, endDateVal, durations, medVal])

    //新建和修改的响应
    const publicResponse = (res, content) => {
        if(res.status === 1) {
            //添加成功
            Toast.show({
                content: content,
                position: 'bottom'
            });
            const timeout = setTimeout(() => {
                clearTimeout(timeout);
                if(location.state.page === "home") {
                    navigator("/medication", {replace: true})
                } else {
                    navigator(-1);
                }
            }, 1000);
        } else {
            Toast.show({
                content: `${res.msg}`,
                position: 'center'
            });
        }
    }


    //点击底部保存按钮
    const clickAddMedBtn = () => {
        if(!addmDisabled) {return;}
        const param = {
            start: startDateVal,  //开始日期
            end: endDateVal,    //结束日期
            times: durations,  //服药时间
            drugs: medVal,  //药品
            remark: supplyVal, //备注
            warn: typeof tipSwitch === "boolean" ? (tipSwitch === true ? 1 : 0) : tipSwitch //是否提醒
        }
        //添加
        if(location.state?.type === "add") {
            addUserTakings(null, param).then(res => {
                publicResponse(res, "保存成功");
            })
            return;
        }

        //修改
        addUserTakings(detail.get("index"), param).then(res => {
            publicResponse(res, "保存成功");
        })
    }

    //点击底部删除按钮
    const clickDelMedBtn = () => {
        delUserTakings(detail.get("index")).then(res => {
            publicResponse(res, "删除成功");
        })
    }


    return (
        <div className='addmContainer'>

            <HeadBack background={"#FFFFFF"} backTit={""}  isHome="back"></HeadBack>

            {/* 用药提醒头部 */}
            <div className='addmHead'>

                <div className='addmHeadTitBox'>
                    {/* 标题 */}
                    <div className='addmHeadTit'>
                        <div className='addmHeadUnitBox'><img alt='' src={unitImg} className='addmHeadUnit' /></div>
                        <div className='addmHeadTip'>用药时间</div>
                    </div>

                    {/* 开始时间和结束时间 */}
                    <div className='addmHeadDate'>
                        <div className='addmHeadStart' onClick={() => clickItem(0)}>{startDateVal === "" ? "开始时间" : startDateVal}</div>
                        <div className='addmHeadDateLine'></div>
                        <div className='addmHeadStart' onClick={() => clickItem(1)}>{endDateVal === "" ? "结束时间" : endDateVal}</div>
                    </div>
                </div>

                {/* 选择小时分钟分钟 */}
                <div className='addDuration'>
                    {
                        durations.map((item, index) => (
                            <div className='addDurationLi' key={index}>
                                <span>{item}</span>
                                <img alt='' src={closeDurImg} className='addCloseIcon' onClick={() => clickDelDurItem(index)} />
                            </div>
                        ))
                    }
                    
                    <div className={`addDurationLiAdd ${durations.length >= 8 && 'popHidden'}`} onClick={() => clickItem(2)}>
                        <img alt='' src={addDurImg} className='addDurationIcon' />
                        <span>添加</span>
                    </div>
                </div>
            </div>

            {/* 用什么药备注 */}
            <div className='addmHead addmUse'>
                <div className='addmHeadTitBox'>
                    {/* 标题 */}
                    <div className='addmHeadTit'>
                        <div className='addmHeadUnitBox'><img alt='' src={unitImg} className='addmHeadUnit' /></div>
                        <div className='addmHeadTip'>用什么药</div>
                    </div>
                </div>
  
                <div className='addmTit'>
                    <TextArea value={medVal} onChange={setMedVal} className='addmTitArea' placeholder='可输入药品名称' showCount maxLength={20} rows={1} />
                </div>
            </div>

            {/* 用什么药备注 */}
            <div className='addmHead addmUse'>
                <div className='addmHeadTitBox'>
                    {/* 标题 */}
                    <div className='addmHeadTit'>
                        <div className='addmHeadTip'>备注</div>
                    </div>
                </div>
  
                <div className='addmSupply addSupply'>
                    <TextArea value={supplyVal} onChange={supplyChange} className='addSupplyArea' placeholder='可输入药品用量或者用药注意事项等' showCount maxLength={100} />
                </div>
            </div>

            {/* 提醒 */}
            <div className='addmTipBox'>
                <div className='addmTipTit'>提醒</div>
                <Switch
                    checked={tipSwitch}
                    onChange={setTipSwitch}
                    style={{
                        '--checked-color': '#FF612E',
                        '--height': '0.54rem',
                        '--width': '0.94rem',
                        '--border-width': '4px'
                    }}
                />
            </div>

            {/* 底部的保存按钮 */}
            <div className='memFoot'>

                {/* 新建的时候的按钮 */}
                {
                    location.state.type !== "update" ? (<div className={`addmFootBtn ${addmDisabled && 'addmFootBtnCur'}`} onClick={clickAddMedBtn}>保存</div>) : (
                        <div className='memUpdateFoot'>
                            <div className='memUpdateFootBtn' onClick={clickDelMedBtn}>删除</div>
                            <div className={`memUpdateFootBtn ${addmDisabled && 'addmFootBtnCur'}`} onClick={clickAddMedBtn}>保存</div>
                        </div>
                    )
                }

            </div>



            {/* 性别的弹出框 */}
            <Popup visible={visible} bodyStyle={{ "backgroundColor": "transparent" }} onMaskClick={clickCancel}>
                <div className='hlthGenderModel'>
                    <div className={`hlthGenderBox hlthDateBox`}>
                        {/* 标题 */}
                        <div className='hlthGenderTit'>{popTitList[count]}</div>
                        <CascadePickerView className={`popDate ${count !== 0 && 'popHidden'}`} value={startDate} onChange={startDateChanger} options={targetMap.totalDate} style={dateStyle} />
                        <CascadePickerView className={`popDate ${count !== 1 && 'popHidden'}`} value={endDate} onChange={endDateChanger} options={targetMap.totalDate} style={dateStyle} />
                        <PickerView className={`popGender popDuration ${count !== 2 && 'popHidden'}`} value={durationValue} onChange={durationChanger} columns={targetMap.durationList} style={genderStyle} />
                        {/* 按钮 */}
                        <div className='hlthGenderFoot'>
                            <div className='hlthGenderCancel' onClick={clickCancel}>取消</div>
                            <div className='hlthGenderCancel hlthGenderConfirm' onClick={clickConfirm}>确定</div>
                        </div>
                    </div>
                </div>
            </Popup>
        </div>
    )
}
